const Router = require('koa-router');
const pool = require('../db');
const router = new Router();

console.log('=== Music Router 已加载 ===');
console.log('数据库连接池已导入:', !!pool);

// 获取歌曲列表
router.get('/songs', async (ctx) => {
  console.log('收到请求: GET /songs');
  try {
    const { page = 1, limit = 20, keyword = '', artist = '' } = ctx.query;
    const offset = (page - 1) * limit;
    
    let sql = 'SELECT * FROM songs WHERE 1=1';
    let params = [];
    
    if (keyword) {
      sql += ' AND (title LIKE ? OR artist LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    if (artist) {
      sql += ' AND artist LIKE ?';
      params.push(`%${artist}%`);
    }
    
    sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);
    
    const [songs] = await pool.execute(sql, params);
    
    // 获取总数
    let countSql = 'SELECT COUNT(*) as total FROM songs WHERE 1=1';
    let countParams = [];
    
    if (keyword) {
      countSql += ' AND (title LIKE ? OR artist LIKE ?)';
      countParams.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    if (artist) {
      countSql += ' AND artist LIKE ?';
      countParams.push(`%${artist}%`);
    }
    
    const [countResult] = await pool.execute(countSql, countParams);
    const total = countResult[0].total;
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        songs,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    };
  } catch (error) {
    console.error('获取歌曲列表失败:', error);
    ctx.body = { code: -1, message: '获取歌曲列表失败' };
  }
});

// 获取单个歌曲详情
router.get('/songs/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const [songs] = await pool.execute('SELECT * FROM songs WHERE id = ?', [id]);
    
    if (songs.length === 0) {
      ctx.body = { code: -1, message: '歌曲不存在' };
      return;
    }
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: songs[0]
    };
  } catch (error) {
    console.error('获取歌曲详情失败:', error);
    ctx.body = { code: -1, message: '获取歌曲详情失败' };
  }
});

// 搜索歌曲
router.get('/search', async (ctx) => {
  try {
    const { q, type = 'all' } = ctx.query;
    
    if (!q) {
      ctx.body = { code: -1, message: '搜索关键词不能为空' };
      return;
    }
    
    let sql = 'SELECT * FROM songs WHERE 1=1';
    let params = [];
    
    switch (type) {
      case 'title':
        sql += ' AND title LIKE ?';
        params.push(`%${q}%`);
        break;
      case 'artist':
        sql += ' AND artist LIKE ?';
        params.push(`%${q}%`);
        break;
      case 'all':
      default:
        sql += ' AND (title LIKE ? OR artist LIKE ?)';
        params.push(`%${q}%`, `%${q}%`);
        break;
    }
    
    sql += ' ORDER BY created_at DESC LIMIT 50';
    
    const [songs] = await pool.execute(sql, params);
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: songs
    };
  } catch (error) {
    console.error('搜索歌曲失败:', error);
    ctx.body = { code: -1, message: '搜索歌曲失败' };
  }
});

// 添加歌曲
router.post('/songs', async (ctx) => {
  try {
    const { title, artist, lyrics, song_url, cover_url } = ctx.request.body;
    
    if (!title || !artist || !song_url) {
      ctx.body = { code: -1, message: '歌曲标题、艺术家和音频链接不能为空' };
      return;
    }
    
    const [result] = await pool.execute(
      'INSERT INTO songs (title, artist, lyrics, song_url, cover_url) VALUES (?, ?, ?, ?, ?)',
      [title, artist, lyrics || '', song_url, cover_url || '']
    );
    
    ctx.body = {
      code: 0,
      message: '添加歌曲成功',
      data: { id: result.insertId }
    };
  } catch (error) {
    console.error('添加歌曲失败:', error);
    ctx.body = { code: -1, message: '添加歌曲失败' };
  }
});

// 更新歌曲
router.put('/songs/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { title, artist, lyrics, song_url, cover_url } = ctx.request.body;
    
    const [result] = await pool.execute(
      'UPDATE songs SET title = ?, artist = ?, lyrics = ?, song_url = ?, cover_url = ? WHERE id = ?',
      [title, artist, lyrics, song_url, cover_url, id]
    );
    
    if (result.affectedRows === 0) {
      ctx.body = { code: -1, message: '歌曲不存在' };
      return;
    }
    
    ctx.body = {
      code: 0,
      message: '更新歌曲成功'
    };
  } catch (error) {
    console.error('更新歌曲失败:', error);
    ctx.body = { code: -1, message: '更新歌曲失败' };
  }
});

// 删除歌曲
router.delete('/songs/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    
    const [result] = await pool.execute('DELETE FROM songs WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      ctx.body = { code: -1, message: '歌曲不存在' };
      return;
    }
    
    ctx.body = {
      code: 0,
      message: '删除歌曲成功'
    };
  } catch (error) {
    console.error('删除歌曲失败:', error);
    ctx.body = { code: -1, message: '删除歌曲失败' };
  }
});

// 获取推荐歌曲
router.get('/recommend', async (ctx) => {
  try {
    const [songs] = await pool.execute(
      'SELECT * FROM songs ORDER BY RAND() LIMIT 10'
    );
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: songs
    };
  } catch (error) {
    console.error('获取推荐歌曲失败:', error);
    ctx.body = { code: -1, message: '获取推荐歌曲失败' };
  }
});

// 获取热门歌曲
router.get('/hot', async (ctx) => {
  try {
    const [songs] = await pool.execute(
      'SELECT * FROM songs ORDER BY created_at DESC LIMIT 20'
    );
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: songs
    };
  } catch (error) {
    console.error('获取热门歌曲失败:', error);
    ctx.body = { code: -1, message: '获取热门歌曲失败' };
  }
});

// 获取艺术家列表
router.get('/artists', async (ctx) => {
  try {
    const [artists] = await pool.execute(
      'SELECT DISTINCT artist FROM songs ORDER BY artist'
    );
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: artists.map(item => item.artist)
    };
  } catch (error) {
    console.error('获取艺术家列表失败:', error);
    ctx.body = { code: -1, message: '获取艺术家列表失败' };
  }
});

module.exports = router;